#include <iostream>
#include <unistd.h>
#include <cassert>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <cstring>
#include <errno.h>

using namespace std;

#define MAX 1024

int main()
{
    //1.创建管道
    int pipefd[2] = {0};
    pipe(pipefd); 
    
    //2.创建子进程
    pid_t id = fork();
    if(id < 0)
    {
        perror("fork:");
        return 1;
    }
    
    //3.父子进程分别关闭写、读端
    if(0 == id)
    {
        //child
        close(pipefd[0]); //关闭读端
        int cnt = 0;
        char c = 'a';
        while(true)
        {
            write(pipefd[1], &c, 1); //最后一个参数表示写的字符串的大小(有效字符个数)
            cnt++;
            cout << "child write....." << cnt << endl;
        }
    }

    //father
    close(pipefd[1]); //关闭写端
    char buffer[MAX];
    while(true)
    {
        sleep(200);
        ssize_t n = read(pipefd[0], buffer, sizeof(buffer)-1); //最后一个参数表示缓冲区大小,最后一个位置默认要放\0
        if(n > 0)
        {
            buffer[n] = 0; //read读取的不一定当字符串处理, 手动添加0当字符串处理
            cout << "I am father, pid:" <<  getpid() << ", child say: " << buffer << endl;
        }
    }
    
    pid_t rid = waitpid(id, NULL, 0);
    if(rid == id)
    {
        cout << "wait success!" << endl;
    }
    return 0;
}


